<?php
namespace app\mini\model;

use app\admin\model\PersonModel;
use app\crm\model\Customer;
use app\mini\controller\QyWechatController;
use think\facade\Db;
use app\common\traits\ActionRecordTrait;
use think\Model;
use app\admin\controller\ApiCommon;
//use app\mini\controller\QyWechatController;

use app\crm\model\CustomerLossModel;
use app\crm\model\OrderStatistics;
use app\admin\model\ShopOrderModel;
use app\admin\model\CustomerModel;
use app\admin\model\ShopModel;
use app\shop\model\Refund as OrderModel;
use app\mini\model\MiniStisticsModel;
use app\mini\model\CustomerPointGoodsBuy;



class SysModelMiniCustomer extends Model

{
    /**

     * @var string

     */

    protected $name = 'admin_sys';


    protected $defaultSoftDelete = 0;


    protected $autoWriteTimestamp = true;


    /**

     * 新增客户服务评价

     * @return array

     * @author ran

     * @date 2021-09-23 13:53

     * mailbox 466180170@qq.com

     */
    public function addEvaluation($request): array
    {
        $create_time = time();

        $customer_id = $request['customerId'];
        $serviceLog_id = $request['rateId'];
        $scoreValue = $request['rateValue'];
        $rate_text = $request['rateText'];
        $score_one = $request['score_one']??null;
        $score_two = $request['score_two']??null;
        $score_three = $request['score_three']??null;
        $score_four = $request['score_four']??null;
        $score_five = $request['score_five']??null;
        $wenjuan = $request['wenjuan']??1;


        if($scoreValue == '1'){
            $score_amount = '0';
        }else if($scoreValue == '2'){
            $score_amount = '40';
        }else if($scoreValue == '3'){
            $score_amount = '60';
        }else if($scoreValue == '4'){
            $score_amount = '80';
        }else if($scoreValue == '5'){
            $score_amount = '100';
        }

        $shop_id = Db::name('customer')->where('id',$customer_id)->value('shop_id');



        // $data = [
        //     'servicelog_id' => $serviceLog_id,
        //     'customer_id'   => $customer_id,
        //     'shop_id'       => $shop_id,
        //     'score_amount'  => $score_amount,
        //     'rate_text'     => $rate_text,
        //     'score_one'     =>$score_one,
        //     'score_two'     =>$score_two,
        //     'score_three'   =>$score_three,
        //     'score_four'    =>$score_four,
        //     'create_time'   => $create_time,
        // ];


        try {

            $is_evalution = Db::name('service_log')->where('id', $serviceLog_id)->column('is_evaluation,book_id');

            if($is_evalution[0]['is_evaluation'] == '0'){

                $where = [];

                if($is_evalution[0]['book_id']){

                    array_push($where,['book_id','=',$is_evalution[0]['book_id']]);

                    $serviceLogs = Db::name('service_log')->where($where)->select()->toArray();

                    foreach ($serviceLogs as $key => $value) {

                        $data = [];

                        $data = [
                            'servicelog_id' => $value['id'],
                            'customer_id'   => $customer_id,
                            'shop_id'       => $shop_id,
                            'score_amount'  => $score_amount,
                            'rate_text'     => $rate_text,
                            'wenjuan'       => $wenjuan,
                            'score_one'     => $score_one,
                            'score_two'     => $score_two,
                            'score_three'   => $score_three,
                            'score_four'    => $score_four,
                            'score_five'    => $score_five,
                            'create_time'   => $create_time,
                        ];

                        $rate_id = Db::name('service_log_evaluation')->insertGetId($data);

                        if($rate_id){

                            $updateArr = [
                                'is_evaluation' => 1,
                            ];

                            $bool = Db::name('service_log')->where(['id' => $value['id']])->update($updateArr);

                        }

                    }
                }else{

                    $data = [];

                    $data = [
                        'servicelog_id' => $serviceLog_id,
                        'customer_id'   => $customer_id,
                        'shop_id'       => $shop_id,
                        'score_amount'  => $score_amount,
                        'rate_text'     => $rate_text,
                        'wenjuan'       => $wenjuan,
                        'score_one'     => $score_one,
                        'score_two'     => $score_two,
                        'score_three'   => $score_three,
                        'score_four'    => $score_four,
                        'score_five'    => $score_five,
                        'create_time'   => $create_time,
                    ];



                    $rate_id = Db::name('service_log_evaluation')->insertGetId($data);

                    if($rate_id){

                        $updateArr = [
                            'is_evaluation' => 1,
                        ];

                        $bool = Db::name('service_log')->where(['id' => $serviceLog_id])->update($updateArr);

                    }

                }



                $where = [];
                $date = strtotime((date("Y-m",time())));
//                array_push($where,['origin_id','=',8]);
                array_push($where,['customer_id','=',$customer_id]);
                array_push($where,['create_time','>=',$date]);
                $evaluation = Db::name('service_log_evaluation')->where($where)->count();
                $where = [];
                array_push($where,['id','=',$serviceLog_id]);
                $serviceTime = Db::name('service_log')->where($where)->value('create_time');
                if(empty($serviceTime))
                {
                    $serviceTime=0;
                }
                if($serviceTime>=1694707200){
                    if(empty($evaluation))
                    {
                        CustomerPointModel::pointChange($customer_id,8);

                    }else{
                        CustomerPointModel::pointChange($customer_id,7);

                    }
                }

                return ['error' => '评价成功'];

            }else{

                return ['error' => '该服务您已经评价过了，请勿重复提交'];

            }



        } catch (\Throwable $e) {

            return ['error' => $e->getMessage()];

        }

    }

    public function addEvaluationCeShi($request): array
    {

        $create_time = time();

        $customer_id = $request['customerId'];
        $serviceLog_id = $request['rateId'];
        $scoreValue = $request['rateValue'];
        $rate_text = $request['rateText'];
        $score_one = $request['score_one']??null;
        $score_two = $request['score_two']??null;
        $score_three = $request['score_three']??null;
        $score_four = $request['score_four']??null;


        if($scoreValue == '1'){
            $score_amount = '0';
        }else if($scoreValue == '2'){
            $score_amount = '40';
        }else if($scoreValue == '3'){
            $score_amount = '60';
        }else if($scoreValue == '4'){
            $score_amount = '80';
        }else if($scoreValue == '5'){
            $score_amount = '100';
        }

        $shop_id = Db::name('customer')->where('id',$customer_id)->value('shop_id');

        // $data = [
        //     'servicelog_id' => $serviceLog_id,
        //     'customer_id'   => $customer_id,
        //     'shop_id'       => $shop_id,
        //     'score_amount'  => $score_amount,
        //     'rate_text'     => $rate_text,
        //     'score_one'     =>$score_one,
        //     'score_two'     =>$score_two,
        //     'score_three'   =>$score_three,
        //     'score_four'    =>$score_four,
        //     'create_time'   => $create_time,
        // ];

        // echo "<pre>";
        // print_r($data);
        // echo "</pre>";
        // exit;
        // try {

            $is_evalution = Db::name('service_log')->where('id', $serviceLog_id)->column('is_evaluation,book_id');

            // echo "<pre>";
            // print_r($is_evalution);
            // echo "</pre>";
            // exit;

            if($is_evalution[0]['is_evaluation'] == '0'){


                $where = [];

                array_push($where,['book_id','=',$is_evalution[0]['book_id']]);

                $serviceLogs = Db::name('service_log')->where($where)->select()->toArray();

                // echo "<pre>";
                // print_r($serviceLogs);
                // echo "</pre>";
                // exit;

                foreach ($serviceLogs as $key => $value) {

                    $data = [];

                    $data = [
                        'servicelog_id' => $value['id'],
                        'customer_id'   => $customer_id,
                        'shop_id'       => $shop_id,
                        'score_amount'  => $score_amount,
                        'rate_text'     => $rate_text,
                        'score_one'     =>$score_one,
                        'score_two'     =>$score_two,
                        'score_three'   =>$score_three,
                        'score_four'    =>$score_four,
                        'create_time'   => $create_time,
                    ];

                    $rate_id = Db::name('service_log_evaluation')->insertGetId($data);

                    if($rate_id){

                        $updateArr = [
                            'is_evaluation' => 1,
                        ];

                        $bool = Db::name('service_log')->where(['id' => $value['id']])->update($updateArr);

                    }

                }


                if(!empty($request['is_first']))
                {
                    CustomerPointModel::pointChange($customer_id,8);

                }else{
                    CustomerPointModel::pointChange($customer_id,7);

                }

                return ['error' => '评价成功'];

            }else{

                return ['error' => '该服务您已经评价过了，请勿重复提交'];

            }



        // } catch (\Throwable $e) {

        //     return ['error' => $e->getMessage()];

        // }

    }


    public function getScheduleList($request)
    {
        // 验证必需参数
        if (empty($request['staffIds'])) {
            $this->error = "员工ID列表不能为空";
            return false;
        }
        
        $staffIds = $request['staffIds'];
        $year = date('Y');
        $month = date('m');
        
        // 计算日期范围 (今天开始15天)
        $dateList = [];
        for ($i = 0; $i < 15; $i++) {
            $timestamp = time() + 86400 * $i;
            $dateList[] = [
                'db_date' => date('Ymd', $timestamp), // 数据库格式: 20250603
                'display_date' => date('m-d', $timestamp) // 显示格式: 06-03
            ];
        }
        // 获取员工基本信息
        $staffList = Db::name('shop_person')
            ->where('id', 'in', $staffIds)
            ->field('id, name')
            ->select()
            ->toArray();
        
        if (empty($staffList)) {
            $this->error = "未找到员工信息";
            return false;
        }
        
        // 获取排班数据
        $dbDates = array_column($dateList, 'db_date');
        $schedules = Db::name('shop_person_schedule')
            ->where('shop_person_id', 'in', $staffIds)
            ->where('time', 'in', $dbDates)
            ->field('id, shop_person_id, time, is_work, work_type')
            ->select()
            ->toArray();
        // 构建排班数据映射表 [员工ID][日期] => 排班状态
        $scheduleMap = [];
        foreach ($schedules as $schedule)
        {
            $staffId = $schedule['shop_person_id'];
            $date = $schedule['time'];
            
            // 确定排班状态
            if ($schedule['is_work'] == 0) {
                $status = 0; // 休息
            } else {
                // 上班状态
                switch ($schedule['work_type'])
                {
                    case 0: $status = 1; break; // 全天班
                    case 1: $status = 2; break; // 上午班
                    case 2: $status = 3; break; // 下午班
                    default: $status = 0; // 否则默认休息
                }
            }
            
            $scheduleMap[$staffId][$date] = $status;
        }
        
        // 构建返回数据结构
        $result = [];
        foreach ($staffList as $staff)
        {
            $staffId = $staff['id'];
            $item = [
                'id' => $staffId,
                'name' => $staff['name'],
                'year' => $year
            ];
            
            // 初始化每天的状态
            foreach ($dateList as $date)
            {
                $dbDate = $date['db_date'];
                $displayDate = $date['display_date'];
                
                // 如果有排班记录则使用，否则默认休息(0)
                $item[$displayDate] = $scheduleMap[$staffId][$dbDate] ?? 0;
            }
            
            $result[] = $item;
        }
        return ['msg' => '成功', 'data' => $result,'code'=>200];
    }

    // 员工排班
    public function setSchedule($request)
    {
        // 数据验证
        $requiredFields = [
            'shop_id' => '门店ID',
            'time' => '预约日期',
            'shop_person_id' => '员工ID',
            'is_work' => '排班类型 - 休息/上班',
            'work_type' => '排班类型 - 全天班/上午班/下午班',
            'kk_time' => '可预约时间段'
        ];
        
        foreach ($requiredFields as $field => $name) {
            if (!isset($request[$field])) {
                $this->error = $name . '不能为空';
                return false;
            }
        }
        
        // 查询该员工当天是否已经排过班
        $schedule = Db::name('shop_person_schedule')
            ->where('shop_person_id', $request['shop_person_id'])
            ->where('time', $request['time'])
            ->find();
        
        // 处理休息状态
        if ($request['is_work'] == 0) {
            if ($schedule) {
                // 检查是否已有预约
                $yy_time_arr = json_decode($schedule['yy_time'], true);
                
                if (!empty($yy_time_arr)) {
                    // 存在预约记录，不允许直接休息
                    $this->error = "该员工已有预约，请先联系客户取消预约";
                    return false;
                } else {
                    // 无预约记录，清空时间段
                    $request['kk_time'] = json_encode([]);
                    $request['dd_time'] = json_encode([]);
                    $request['update_time'] = time();
                    $res = Db::name('shop_person_schedule')->where('id', $schedule['id'])->update($request);
                }
            } else {
                // 新休息记录
                $request['kk_time'] = json_encode([]);
                $request['dd_time'] = json_encode([]);
                $request['create_time'] = time();
                $res = Db::name('shop_person_schedule')->insert($request);
            }
        } 
        // 处理上班状态
        else {
            if ($schedule) {
                // 检查是否已被预约
                $appointmentError = false;
                $yy_time_arr = json_decode($schedule['yy_time'], true);
            
                if (!empty($yy_time_arr)) {
                    foreach ($yy_time_arr as $appointedTime) {
                        if (!in_array($appointedTime, $request['kk_time'])) {
                            $appointmentError = true;
                            break;
                        }
                    }
                }
                
                if ($appointmentError) {
                    $this->error = "修改失败：已存在预约记录，且新的可预约时间段不包含所有已预约时段";
                    return false;
                } else {
                    $request['update_time'] = time();
                    $request['kk_time'] = !empty($request['kk_time']) ? json_encode($request['kk_time']) : json_encode([]);
                    $request['dd_time'] = !empty($request['dd_time']) ? json_encode($request['dd_time']) : json_encode([]);
                    $res = Db::name('shop_person_schedule')->where('id', $schedule['id'])->update($request);
                }
            } else {
                $request['create_time'] = time();
                $request['kk_time'] = !empty($request['kk_time']) ? json_encode($request['kk_time']) : json_encode([]);
                $request['dd_time'] = !empty($request['dd_time']) ? json_encode($request['dd_time']) : json_encode([]);
                $res = Db::name('shop_person_schedule')->insert($request);
            }
        }
        
        // 返回数据
        if ($res) {
            return ['msg' => '排班成功', 'data' => [], 'code' => 200];
        } else {
            return ['msg' => '排班失败', 'data' => [], 'code' => 200];
        }
    }
    
    

    // 获取客户所属门店的详情
    public function getShopInfo($request): array
    {
        $customer_id = $request['customer_id'];

        $where = [];

        array_push($where,['id','=',$customer_id]);

        $shopId = Db::name('customer')->where($where)->value('shop_id');

        $shop_where = [];

        array_push($shop_where,['shop_id','=',$shopId]);

        $shopInfo = Db::name('shop')->where($shop_where)->select()->toArray();

        // echo "<pre>";
        // print_r($shopInfo);
        // echo "</pre>";

        $shop_name  = !empty($shopInfo)?$shopInfo[0]['shop_name']:'';

        $shop_tel   = !empty($shopInfo)?$shopInfo[0]['shop_phone']:'';

        $start_time =!empty($shopInfo)? $shopInfo[0]['start_time']:'';

        $end_time   = !empty($shopInfo)?$shopInfo[0]['end_time']:'';

        $address    = !empty($shopInfo)?$shopInfo[0]['address']:'';
        $type = !empty($shopInfo)?$shopInfo[0]['type']:0;

        $shop_type = !empty($shopInfo)?$shopInfo[0]['shop_type']:0;

        $data = [

            'shop_id' => !empty($shopInfo)?$shopId:0,

            'shop_name' => $shop_name,

            'shop_tel' => $shop_tel,

            'start_time' => $start_time,

            'end_time' => $end_time,

            'address' => $address,
            'type' =>$type,
            'shop_type' =>$shop_type

        ];

        // exit;

        return $data;
    }

    // 获取可预约日期
    public function bookDate(): array
    {

        $weekdays = array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');

        $today = date("Y-m-d",time());

        $todayTimeStr = strtotime($today);


        $dateList = [];

        for($i=0;$i<=7;$i++){

            $timeStr = $todayTimeStr+86400*$i;

            $one = [];

            $one['year'] = date('Y',$timeStr);

            $one['month'] = date('m',$timeStr);

            $one['day'] = date('d',$timeStr);

            $one['date'] = $one['month'].'-'.$one['day'];

            $one['weekday'] = $weekdays[date('w',$timeStr)];

            array_push($dateList,$one);

        }

        return $dateList;

    }

    public function bookTime($request): array
    {

        // $shop_id = $request['shop_id'];

        // $start_time = $request['start_time'];

        // $end_time = $request['end_time'];

        // $year = $request['year'];

        // $date = $request['date'];

        // $timeStr = strtotime($year.'-'.$date); // 查询当天时间戳

        // $time = date('Ymd',$timeStr); // 查询当天日期

        // $where = [];

        // array_push($where,['shop_id','=',$shop_id]);

        // array_push($where,['time','=',$time]);

        // array_push($where,['is_work','=','1']);

        // $staffWorkList = Db::name('shop_person_schedule')->where($where)->select()->toArray();

        // // echo "<pre>";
        // // print_r($staffWorkList);
        // // echo "</pre>";

        // $list = [];

        // if($staffWorkList){
        //     // 有排班

        //     $yy = str_split($staffWorkList[0]['yy_time']);

        //     // echo "<pre>";
        //     // print_r($yy);
        //     // echo "</pre>";

        //     // $startWorkTime = $year.'-'.$date.' '.$start_time;

        //     // echo $startWorkTime;
        //     // exit;

        //     $startWorkTimeStr = strtotime($year.'-'.$date.' '.$start_time); // 查询当天开始工作时间

        //     $endWorkTimeStr = strtotime($year.'-'.$date.' '.$end_time); // 查询当天开始工作时间

        //     foreach ($yy as $key => $value) {

        //         $one = [];

        //         // $showTimeStr = $startWorkTimeStr+$key*3600; // 时间间隔为1小时
        //         $showTimeStr = $startWorkTimeStr+$key*1800; // 时间间隔为半小时

        //         $showTime = date('H:i',$showTimeStr);

        //         if($showTimeStr>time() && $showTimeStr<$endWorkTimeStr){

        //             $is_yy = 1;

        //         }else{

        //             $is_yy = 0;

        //         }

        //         $one['showTime'] = $showTime;

        //         $one['is_yy'] = $is_yy;

        //         $one['id'] = 'time'.$key.$year;

        //         array_push($list,$one);

        //     }




        // }else{
        //     // 无排班
        // }

        // // foreach ($staffWorkList as $key => $value) {


        // // }

        // // exit;

        // return [
        //     'data' => $list,
        // ];
    }

    public function bookTime2($request): array
    {
        // 验证必需参数
        $requiredFields = [
            'shop_person_id' => '员工ID',
            'shop_id' => '店铺ID',
            'time' => '日期'
        ];
        
        foreach ($requiredFields as $field => $name)
        {
            if (empty($request[$field])) {
                return json(['code' => 400, 'msg' => $name . '不能为空']);
            }
        }
    
        $result = [];
        // 获取当前时间（用于时间段有效性验证）
        $currentTime = time();
        // 现在可以安全访问这些参数
        $schedule = Db::name('shop_person_schedule')
            ->where('shop_person_id', $request['shop_person_id'])
            ->where('shop_id', $request['shop_id'])
            ->where('time', $request['time'])
            ->field('kk_time, yy_time, dd_time')
            ->find() ?: []; // 确保 $schedule 总是数组
            
        // 处理时间格式
        $dateString = $request['time'];
        // 将数字转换为字符串，确保格式正确
        $dateString = (string)$dateString;
        // 分割年月日
        $year = substr($dateString, 0, 4);
        $month = substr($dateString, 4, 2);
        $day = substr($dateString, 6, 2);
        // 组合成"YYYY-MM-DD 00:00:00"格式
        $start_time = "{$year}-{$month}-{$day} 00:00:00";
        $end_time = "{$year}-{$month}-{$day} 23:59:59";
        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        // 查询已核销的数据
        $books = Db::name('books')
            ->where('shop_person_id', $request['shop_person_id'])
            ->where('shop_id', $request['shop_id'])
            ->where('yy_time','>=',$start_time)
            ->where('yy_time','<=',$end_time)
            ->where('is_use',1)
            ->select();
        if(!empty($books))
        {
            // 从books结果中提取所有yy_time_str并合并到yyTime数组
            $bookedSlots = [];
            foreach ($books as $book) {
                if (!empty($book['yy_time_str'])) {
                    // 分割逗号分隔的字符串并去除空格
                    $slots = array_map('trim', explode(',', $book['yy_time_str']));
                    $bookedSlots = array_merge($bookedSlots, $slots);
                }
            }
        }
        
        // 处理结果
        if (empty($schedule))
        {
            return $result;
            exit;
        }
    
        // 解析JSON数据，处理可能的空值
        $kkTime = json_decode($schedule['kk_time'] ?? '[]', true) ?: [];
        $yyTime = json_decode($schedule['yy_time'] ?? '[]', true) ?: [];
        $ddTime = json_decode($schedule['dd_time'] ?? '[]', true) ?: [];
        if(!empty($bookedSlots))
        {
            $yyTime = array_merge($bookedSlots, $yyTime);
        }
        
        // 统计每个时间段的预约次数
        $timeSlotCounts = array_count_values($yyTime);
        
        // 准备日期格式转换（YYYYMMDD -> YYYY-MM-DD）
        $year = substr($request['time'], 0, 4);
        $month = substr($request['time'], 4, 2);
        $day = substr($request['time'], 6, 2);
        $formattedDate = "{$year}-{$month}-{$day}";
        
        // 构建返回数据
        foreach ($kkTime as $timeSlot) {
            // 是否已预约
            $isYy = in_array($timeSlot, $yyTime) ? 1 : 0;
            
            // 是否重复时间段
            $isDd = in_array($timeSlot, $ddTime) ? "1" : "0";
            
            // 是否约满（重复时间段且已被预约两次）
            $isFill = "0"; // 默认未约满
            if ($isDd === "1") {
                // 检查该时间段是否已被预约两次
                $count = $timeSlotCounts[$timeSlot] ?? 0;
                $isFill = ($count >= 2) ? "1" : "0";
            }
            
            // 检查时间段是否已过期（超过当前时间）
            $isInvalid = 0;
            // 组合完整时间戳：日期 + 时间段（如 "2025-06-14 09:30"）
            $timeSlotFull = "{$formattedDate} {$timeSlot}";
            $timeSlotStamp = strtotime($timeSlotFull);
            
            if ($timeSlotStamp <= $currentTime) {
                $isInvalid = 1;
            }
            
            $result[] = [
                'showTime' => $timeSlot, // 当前时间段
                'is_yy' => $isYy,       // 是否预约
                'is_dd' => $isDd,       // 是否重复时间段
                'is_fill' => $isFill,   // 是否约满
                'is_invalid' => $isInvalid // 是否失效（1=已过期，0=有效）
            ];
        }
        
        return $result;
    }

    public function getYYStaff($request): array
    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";

        $year = $request['year'];

        $date = $request['date'];

        $shop_id = $request['shop_id'];

        $showYYTime = $request['showYYTime'];

        $timeStr = strtotime($year.'-'.$date); // 查询当天时间戳

        $time = date("Ymd",$timeStr);

        // 门店上下班时间
        $start_time = Db::name('shop')->where('shop_id',$shop_id)->value('start_time');

        // echo "<pre>";
        // print_r($shop_info);
        // echo "</pre>";

        $startWorkTimeStr = strtotime($year.'-'.$date.' '.$start_time); // 查询当天开始工作时间

        $yy_this_time = strtotime($year.'-'.$date.' '.$showYYTime); // 查询当天开始工作时间

        $subTime = bcsub($yy_this_time,$startWorkTimeStr,0);

        $numKey = floor($subTime/1800); // 预约时间在‘yy_time’中的位数（key值，第一个为0，第二个为1，。。。）

        $where = [];

        array_push($where,['position_id','in',[2,4,7,8,9,10]]);

        array_push($where,['shop_id','=',$shop_id]);

        array_push($where,['status','=','1']); // 在职

        $staffList = Db::name('shop_person')->where($where)->column('id,name,station_name,position_name,shop_id');

        // echo "<pre>";
        // print_r($staffList);
        // echo "</pre>";
        // exit;

        $where = [];

        array_push($where,['time','=',$time]);

        array_push($where,['shop_id','=',$shop_id]);

        $paiBanList = Db::name('shop_person_schedule')->where($where)->column('yy_time,shop_person_id,is_work','shop_person_id');

        // echo "<pre>";
        // print_r($paiBanList);
        // echo "</pre>";
        // exit;


        $shop_person_ids = array_values(array_unique(array_column($paiBanList,'shop_person_id')));

        $where = [];

        array_push($where,['shop_person_id','in',$shop_person_ids]);

        $shop_person_names = Db::name('admin_user')->where($where)->column('img','shop_person_id');

        // echo "<pre>";
        // print_r($shop_person_names);
        // echo "</pre>";
        // exit;


        $list = [];

        foreach ($staffList as $key => $value) {

            $one = [];

            $one['id'] = $value['id'] ?? '';

            $one['name'] = $value['name'] ?? '';

            $one['station_name'] = $value['station_name'] ?? '';

            $one['position_name'] = $value['position_name'] ?? '';

            $one['img'] = $shop_person_names[$value['id']] ?? '';

            $isPaiBan = $paiBanList[$value['id']]['yy_time'] ?? '';

            if($isPaiBan){

                if($paiBanList[$value['id']]['is_work'] == '1'){ // $isPaiBan ||

                    $yy_time_list = str_split($isPaiBan);

                    if($yy_time_list[$numKey]<1){ // 单位时间内预约的人数

                        $one['is_yy'] = 1;

                    }else if($yy_time_list[$numKey] == 1){ // 单位时间内预约的人数

                        $one['is_yy'] = 2;

                    }

                }else{

                    $one['is_yy'] = 0;

                }

            }else{

                $one['is_yy'] = 0;

            }


            array_push($list,$one);

        }

        return [

            'msg' => 'model',

            'data' => $list,

        ];
    }

    // 新增预约
    public function addYYData($request):array
    {


        // $customer_id = $request['customer_id'];

        // if($customer_id < 1){

        //     return ['msg' => '获取登陆人信息失败，请重新授权登录！'];
        //     exit;

        // }

        // $shop_person_id = $request['shop_person_id'];

        // $year = $request['yy_year'];

        // $date = $request['yy_date'];

        // $time = $request['yy_time'];

        // $shop_id = $request['shop_id'];

        // $addRes = $this->addNewData($customer_id,$shop_person_id,$year,$date,$time,$shop_id);

        // if($addRes['msg'] == '预约成功！'){

        //     // echo "修改员工排班数据";
        //     $bookRes = $this->updateStaffData($shop_person_id,$year,$date,$time,$shop_id,'add');

        //     return ['msg' => '预约成功！'];

        // }else{

        //     return ['msg' => $addRes['msg']];

        // }

        return ['msg' => '请清除小程序的缓存，如有问题请联系门店！'];

    }

    // 新增预约
    public function addYYData2($request,$app):array
    {
        
         // 验证必需参数
        $requiredFields = [
            'customer_id' => '客户ID',
            'shop_person_id' => '员工ID',
            'yy_year' => '预约年份',
            'yy_date' => '预约日期',
            'yy_time' => '预约时间',
            'shop_id' => '门店ID'
        ];
        
        foreach ($requiredFields as $field => $name)
        {
            if (empty($request[$field]))
            {
                return ['error' => $name . '不能为空'];
            }
        }
        
        // 组合预约日期
        $appointmentDate = strtotime($request['yy_year'] . '-' . $request['yy_date']);
        $today = strtotime(date('Y-m-d')); // 获取当前日期（不含时间）
        
        // 1. 验证是否为有效日期
        if ($appointmentDate === false)
        {
            return ['error' => '预约日期格式无效'];
        }
        
        // 2. 禁止预约过去日期
        if ($appointmentDate < $today)
        {
            return ['error' => '不能预约过去的日期'];
        }
        
        // 3. 可选：禁止当天过期时段（根据业务需求）
        $currentTime = time();
        if ($appointmentDate == $today)
        {
            $firstTimeSlot = strtotime(date('Y-m-d') . ' ' . $request['yy_time'][0]);
            if ($firstTimeSlot < $currentTime)
            {
                return ['error' => '当前时段已过期，请选择其他时间'];
            }
        }
        
        
        // 组合完整日期
        $fullDate = date('Ymd',strtotime($request['yy_year'] . '-' . $request['yy_date']));
        
        // 开启事务
        Db::startTrans();
        try {
            // 1. 查询员工排班信息
            $schedule = Db::name('shop_person_schedule')
                ->where('shop_person_id', $request['shop_person_id'])
                ->where('time', $fullDate)
                ->lock(true) // 加锁防止并发
                ->field('kk_time, yy_time, dd_time')
                ->find();
            // 2. 检查是否有排班
            if (!$schedule)
            {
                Db::rollback();
                return ['error' => '该员工当天没有排班'];
            }
            
            // 3. 解析排班数据
            $yyTime = json_decode($schedule['yy_time'] ?? '[]', true) ?: [];
            $ddTime = json_decode($schedule['dd_time'] ?? '[]', true) ?: [];
            
            // 4. 检查每个预约时间段
            foreach ($request['yy_time'] as $timeSlot)
            {
                // 检查是否已预约
                if (in_array($timeSlot, $yyTime))
                {
                    // 检查是否允许重复预约
                    if (!in_array($timeSlot, $ddTime))
                    {
                        Db::rollback();
                        return ['error' => "时间点 {$timeSlot} 已被预约，不可重复预约"];
                    }
                    
                    // +++ 新增：检查同一个客户是否已预约该时间段 +++
                    $customerBooked = Db::name('books')
                        ->where('customer_id', $request['customer_id'])
                        ->where('shop_person_id', $request['shop_person_id'])
                        ->where('yy_time', strtotime($request['yy_year'] . '-' . $request['yy_date'] . ' ' . $timeSlot))
                        ->where('status', 0) // 只检查正常预约状态
                        ->count();
                    
                    if ($customerBooked > 0)
                    {
                        Db::rollback();
                        return ['error' => "您已预约过时间点 {$timeSlot}，不可重复预约", 'data' => []];
                    }
                    // --- 结束新增 ---
                    
                    // 检查重复预约次数限制
                    $existingCount = Db::name('books')
                        ->where('shop_person_id', $request['shop_person_id'])
                        ->where('yy_time', strtotime($request['yy_year'] . '-' . $request['yy_date'] . ' ' . $timeSlot))
                        ->where('status', 0) // 只计算正常预约
                        ->count();
                    
                    // 最多允许重复预约2次
                    if ($existingCount >= 2)
                    { 
                        Db::rollback();
                        return ['error' => "时间点 {$timeSlot} 重复预约次数已达上限", 'data' => []];
                    }
                }
            }
            
            // 5. 执行预约操作
            $addRes = $this->addNewData2(
                $request['customer_id'],
                $request['shop_person_id'],
                $request['yy_year'],
                $request['yy_date'],
                $request['yy_time'],
                $request['shop_id']
            );
            
            if ($addRes['msg'] != '预约成功！')
            {
                Db::rollback();
                return ['error' => $addRes['msg']];
            }
            // 6. 更新排班记录中的已预约时间（保留重复时间点）
            // $newYyTime = array_unique(array_merge($yyTime, $request['yy_time']));
            $newYyTime = array_merge($yyTime, $request['yy_time']);
            sort($newYyTime); // 保持时间顺序
            
            $updateData = [
                'yy_time' => json_encode($newYyTime),
                'update_time' => time()
            ];
            
            Db::name('shop_person_schedule')
                ->where('shop_person_id', $request['shop_person_id'])
                ->where('time', $fullDate)
                ->update($updateData);
            
            // 8. 发送企业微信通知
            $qiyeDate = date('Y-m-d',strtotime($request['yy_year'] . '-' . $request['yy_date']));
            $qyWechat = new QyWechatController($app);
            $startTime = $request['yy_time'][0];
            $stopTime = date('H:i', strtotime(end($request['yy_time'])) + 30 * 60);
            
            $res = $qyWechat->index('setReservationAction', [
                'mobile' => Db::name('shop_person')->where('id',$request['shop_person_id'])->value('phone'),
                'start' => $qiyeDate . ' ' . $startTime,
                'end' => $stopTime,
                'customer_name' => Db::name('customer')->where('id',$request['customer_id'])->value('customer_name')
            ]);
            
            // 9. 提交事务
            Db::commit();
            
            return ['error' => '预约成功', 'data' => ['msg' => '取消成功']];
            
        }catch (\Exception $e)
        {
            Db::rollback();
            return ['error' => '预约失败: ' . $e->getMessage()];
        }

    }

    // 预约数据新增数据库
    public function addNewData2($customer_id,$shop_person_id,$year,$date,$time,$shop_id)
    {

        if($time){

            $yyTime = strtotime($year.'-'.$date.' '.$time[0]); // 顾客预约时间戳

        }else{

            return $res = [

                'msg' => 'error!',

            ];

            exit;
        }

        $yy_time_str = implode(',',$time);

        // echo $yy_time_str;
        // exit;

        $where = [];

        array_push($where,['yy_time','=',$yyTime]);

        array_push($where,['customer_id','=',$customer_id]);

        array_push($where,['status','=',0]);


        $bookInfo = Db::name('books')->where($where)->select()->toArray();

        if($bookInfo){ // 请勿重复预约

            $msg = '您已预约当前时间，请勿重复预约！'.$year.'-'.$date.'-'.$time[0];

        }else{

            $data = [

                'customer_id' => $customer_id,

                'shop_person_id' => $shop_person_id,

                'shop_id' => $shop_id,

                'yy_time' => $yyTime,

                'yy_time_str' => $yy_time_str,

                'create_time' => time(),

                'status' => 0, // 0代表正常，1代表取消，

            ];

            $bookId = Db::name('books')->insertGetId($data); // 新增xy_books表数据


            if($bookId){

                $msg = '预约成功！';

            }else{

                $msg = '预约失败，请重新提交！';

            }

        }

        return $res = [

            'msg' => $msg,

        ];

        // exit;
    }

    // 预约数据新增数据库
    public function addNewData($customer_id,$shop_person_id,$year,$date,$time,$shop_id)
    {

        $yyTime = strtotime($year.'-'.$date.' '.$time); // 顾客预约时间戳

        $where = [];

        array_push($where,['yy_time','=',$yyTime]);

        array_push($where,['customer_id','=',$customer_id]);

        array_push($where,['status','=',0]);


        $bookInfo = Db::name('books')->where($where)->select()->toArray();

        if($bookInfo){ // 请勿重复预约

            $msg = '您已预约当前时间，请勿重复预约！!!'.$year.'-'.$date.'-'.$time;

        }else{

            $data = [

                'customer_id' => $customer_id,

                'shop_person_id' => $shop_person_id,

                'shop_id' => $shop_id,

                'yy_time' => $yyTime,

                'create_time' => time(),

                'status' => 0, // 0代表正常，1代表取消，

            ];

            $bookId = Db::name('books')->insertGetId($data); // 新增xy_books表数据


            if($bookId){

                $msg = '预约成功！';

            }else{

                $msg = '预约失败，请重新提交！';

            }

        }

        return $res = [

            'msg' => $msg,

        ];

        // exit;
    }

    // 修改护理师预约看板
    public function updateStaffData($shop_person_id,$year,$date,$time,$shop_id,$type)
    {
        // echo $shop_person_id;
        // echo "<br/>";
        // echo $year;
        // echo "<br/>";
        // echo $date;
        // echo "<br/>";
        // echo $time;
        // echo "<br/>";
        // echo $shop_id;
        // echo "<br/>";

        $dateArr = explode('-',$date);

        // echo "<pre>";
        // print_r($dateArr);
        // echo "</pre>";

        $timeStr = $year.$dateArr[0].$dateArr[1];

        $where = [];

        array_push($where,['shop_person_id','=',$shop_person_id]);

        array_push($where,['time','=',$timeStr]);
		array_push($where,['is_work','=',1]);

        $book_str = Db::name('shop_person_schedule')->where($where)->value('yy_time');

        // echo "<pre>";
        // print_r($where);
        // echo "</pre>";
        // exit;

        $book_arr = str_split($book_str);



        // 门店营业开始时间
        $shop_start_time = Db::name('shop')->where('shop_id',$shop_id)->value('start_time');

        // 门店类型
        $shop_type = Db::name('shop')->where('shop_id',$shop_id)->value('shop_type');

        // echo $shop_start_time;

        $chooseDate = $year.'-'.$date;

        $time1 = strtotime($chooseDate.' '.$shop_start_time);
        $time2 = strtotime($chooseDate.' '.$time);

        // if($shop_person_id == '78'){
        //     echo "time1:".$time1;
        //     echo "<br/>";
        //     echo "time:".$time;
        //     echo "<br/>";
        //     exit;
        // }

        $timeDifference = bcsub($time2,$time1);

        if($shop_type == 1){
            $seconds = 3600;
        }

        if($shop_type == 2){
            $seconds = 1800;
        }

        $key_num = $timeDifference/$seconds;

        // if($shop_person_id == '78'){

        //     echo "<pre>";
        //     print_r($book_arr);
        //     echo "</pre>";
        //     echo "time1:".$key_num;
        //     echo "<br/>";
        //     echo "timeDifference:".$timeDifference;
        //     echo "<br/>";
        //     echo "<br/>";
        //     exit;
        // }

        $thisTimeBookNum = $book_arr[$key_num];



        if($type == 'add'){ // 新增预约

            if($thisTimeBookNum == 0){ // 可以预约

                $book_arr[$key_num] = bcadd($thisTimeBookNum,1,0);

            }else{

                return $time;

            }


        }

        if($type == 'sub'){ // 取消预约

            $book_arr[$key_num] = bcsub($thisTimeBookNum,1,0);

        }

        $new_book_str = implode($book_arr);

        $updateArr = [

            'yy_time' => $new_book_str,

        ];

        // echo "<pre>";
        // print_r($updateArr);
        // echo "</pre>";
        // exit;

        $bool = Db::name('shop_person_schedule')->where($where)->update($updateArr);

        if($bool){
            return true;
        }else{
            return false;
        }




    }

    public function getBookList($request): array
    {
        $where = [];

        array_push($where,['customer_id','=',$request['customer_id']]);
        array_push($where,['is_use','=',0]);
        array_push($where,['status','=',0]); // 未取消的预约
        
        $bookList = Db::name('books')->where($where)->order('yy_time desc')->limit(0,20)->select()->toArray();
        
        $shop_ids = array_values(array_unique(array_column($bookList,'shop_id'))); 
        $where = [];
        array_push($where,['shop_id','in',$shop_ids]);
        $shop_names = Db::name('shop')->where($where)->column('shop_name','shop_id');
        $shop_types = Db::name('shop')->where($where)->column('shop_type','shop_id');
        
        $shop_person_ids =  array_values(array_unique(array_column($bookList,'shop_person_id'))); 
        $where = [];
        array_push($where,['id','in',$shop_person_ids]);
        $shop_person_names = Db::name('shop_person')->where($where)->column('name','id');
        
        $list = [];
        
        foreach ($bookList as $key => $value) {
            // 预约时间戳的前30分钟
            $beforeMinute30 = $value['yy_time'] - (30 * 60);
            $isCancel = (time() < $beforeMinute30) ? 0 : 1;
        
            // 今日日期
            $today = date('Ymd', time());
            // 预约日期
            $yyDate = date('Ymd', $value['yy_time']) ?? '';
            $yy_status = ($yyDate < $today) ? 0 : 1;
        
            // 获取门店的时间设置
            $shop_id = $value['shop_id'];
            $time_default = Db::name('shop')
                ->where('shop_id', $shop_id)
                ->value('time_default') ?: 1; // 默认为半点
        
            // 计算结束时间和时长
            $end_time = '';
            $length = 0;
            
            if (!empty($value['yy_time_str'])) {
                $yy_time_arr = explode(',', $value['yy_time_str']);
                $count = count($yy_time_arr);
                
                // 根据门店设置确定时间间隔
                if ($time_default == 1) {
                    $minutesPerSlot = 30;
                    $hoursPerSlot = 0.5;
                } else {
                    $minutesPerSlot = 60;
                    $hoursPerSlot = 1;
                }
                
                // 计算结束时间
                $lastTimeSlot = end($yy_time_arr);
                $end_time = date('H:i', strtotime($lastTimeSlot) + ($minutesPerSlot * 60));
                
                // 计算总时长
                $length = $count * $hoursPerSlot;
            } else {
                // 根据门店设置确定默认时间间隔
                if ($time_default == 1) {
                    $minutesPerSlot = 30;
                    $hoursPerSlot = 0.5;
                } else {
                    $minutesPerSlot = 60;
                    $hoursPerSlot = 1;
                }
                
                $end_time = date('H:i', $value['yy_time'] + ($minutesPerSlot * 60));
                $length = $hoursPerSlot;
            }
        
            $one = [
                'id' => $value['id'],
                'shop_person_name' => $shop_person_names[$value['shop_person_id']] ?? '',
                'shop_name' => $shop_names[$shop_id] ?? '',
                'yy_date' => date('Y-m-d', $value['yy_time']),
                'yy_time' => date('H:i', $value['yy_time']) . '-' . $end_time,
                'yy_time_str' => $value['yy_time_str'] ?? '',
                'yy_length' => $length,
                'create_time' => date('Y-m-d H:i', $value['create_time']),
                'status' => $value['status'] ?? '',
                'yy_status' => $yy_status,
                'today' => $today,
                'isCancel' => $isCancel
            ];
        
            array_push($list, $one);
        }
        return $list;
    }

    // 客户提交满意度调查接口
    public function addQuestionCustomer($request): array
    {

        // return [
        //     'msg' => '活动已经结束',
        // ];
        $customer_id = $request['customer_id'];
        $customer_info = Db::name('customer')->where('id',$customer_id)->field('shop_id,telephone')->find();

        $shop_id = $customer_info['shop_id'];
        $phone = $customer_info['telephone'];
        $customer_ids = Db::name('customer')->whereIn('telephone',$phone)->column('id');

        $questionId = $request['questionId'];

        $where = [];

        array_push($where,['customer_id','in',$customer_ids]);

        array_push($where,['questionnaire_id','=',$questionId]);

        $question_customer_info = Db::name('question_customer')->where($where)->select()->toArray();

        if(empty($question_customer_info)){
            $answers_arr = $request['answers'];
            $answers = implode(',',$answers_arr);
            addLogs($questionId.'问卷答题'.$customer_id,$answers_arr);
            array_pop($answers_arr);
            addLogs($questionId.'问卷答题'.$customer_id,$answers_arr);
            if(in_array(0,$answers_arr)){
                return [
                    'msg' => '请完善所有问题答案',
                ];
            }

            $data = [

                'customer_id' => $customer_id,

                'questionnaire_id' => $questionId,

                'shop_id' => $shop_id,

                'answers' => $answers,

                'create_time' => time(),

            ];

            $question_customer_id = Db::name('question_customer')->insertGetId($data); // 插入数据库

            if($question_customer_id){

                if($questionId == 7){
                    //司庆问卷答案
                    if($answers == '1,1,1,1,1'){
                        return ['msg' => 'success'];
                    }else{
                        return ['msg' => 'lose'];
                    }
                }

                if($questionId == 8){
                    // 发放产品兑换卷

                    $customerPointGoodsBuy = new CustomerPointGoodsBuy();

                    $customerPointGoodsBuy->save([
                        'point_goods_id'=>'26',
                        'customer_id'=>$customer_id,
                        'status'=>1,
                        'start_time'=>time(),
                        'end_time'=>strtotime('2025-02-28 23:59:59')
                    ]);

                }else{
                    // 获取积分
                    CustomerPointModel::pointChange($customer_id,9);

                }

                return [

                    'msg' => '感谢您对我们的支持！',

                ];

            }else{

                return [

                    'msg' => '数据异常！',

                ];

            }

        }else{

            return [

                'msg' => '请勿重复提交',

            ];

        }

    }


    // 取消预约模型
    public function cancelBook($request,$app): array
    {
        // 验证必需参数
        $requiredFields = [
            'bookId' => '预约记录ID',
            'person' => '取消人',
            'platform' => '取消平台',
            'today' => '预约日期',
            'yy_date' => '预约时间段',
            'yy_time' => '预约时间段'
        ];
        
        foreach ($requiredFields as $field => $name)
        {
            if (empty($request[$field]))
            {
                return ['error' => $name . '不能为空'];
            }
        }
    
        // 获取预约记录
        $bookId = $request['bookId'];
        $bookInfo = Db::name('books')->where('id', $bookId)->find();
        
        if (empty($bookInfo))
        {
            return ['error' => '预约记录不存在'];
        }
        
        // 检查预约状态
        if ($bookInfo['status'] != 0)
        {
            return ['error' => '该预约已取消或已完成'];
        }
        
        // 检查时间段参数
        if (!is_array($request['yy_time']) || count($request['yy_time']) === 0)
        {
            return ['error' => '预约时间段格式错误'];
        }
        $timeSlot = $request['yy_time'][0]; // 取第一个时间段
        
        // 组合预约完整时间戳
        $appointmentTimestamp = strtotime($request['today'] . ' ' . $timeSlot);
        
        // 检查预约时间是否合法
        if ($appointmentTimestamp === false)
        {
            return ['error' => '预约时间格式错误'];
        }
        
        if($request['platform'] == 1)
        {
            // 检查取消时间限制（30分钟）
            $currentTime = time();
            $cancelLimit = $appointmentTimestamp - 1800; // 预约时间前30分钟
            
            if ($currentTime >= $cancelLimit) {
                return ['error' => '临近预约时间半小时内，不可取消预约'];
            }
        }
        
        // 开启事务
        Db::startTrans();
        try {
            // 1. 更新预约记录状态
            $updateData = [
                'status' => 1,
                'cancel_platform' => $request['platform'],
                'cancel_time' => time(),
                'cancel_person' => $request['person']
            ];
            Db::name('books')
                ->where('id', $bookId)
                ->update($updateData);
            
            // 2. 处理排班表
            $schedule = Db::name('shop_person_schedule')
                ->where('shop_person_id', $bookInfo['shop_person_id'])
                ->where('time', $request['today'])
                ->lock(true) // 加锁防止并发
                ->find();
            
            if ($schedule) {
                $yyTime = json_decode($schedule['yy_time'], true) ?: [];
                $originalCount = count($yyTime);
                $modified = false; // 标记是否修改了时间段
                
                // 处理所有取消的时间段
                foreach ($request['yy_time'] as $timeSlot) {
                    // 组合预约完整时间戳
                    $appointmentTimestamp = strtotime($request['today'] . ' ' . $timeSlot);
                    
                    // 检查取消时间限制（30分钟）- 对每个时间段单独检查
                    $currentTime = time();
                    $cancelLimit = $appointmentTimestamp - 1800; // 预约时间前30分钟
                    if($request['platform'] == 1)
                    {
                        if ($currentTime >= $cancelLimit) {
                            Db::rollback();
                            return ['error' => '临近预约时间半小时内，不可取消预约：' . $timeSlot];
                        }
                    }
                    // 直接移除时间段实例，不检查其他预约
                    if (in_array($timeSlot, $yyTime)) {
                        // 定位并移除第一个匹配的时间段
                        $index = array_search($timeSlot, $yyTime);
                        if ($index !== false) {
                            unset($yyTime[$index]);
                            $modified = true;
                        }
                    }
                }
                
                // 如果有时间段被移除，更新排班表
                if ($modified) {
                    $newYyTime = array_values($yyTime); // 重新索引数组保持顺序
                    
                    Db::name('shop_person_schedule')
                        ->where('id', $schedule['id'])
                        ->update([
                            'yy_time' => json_encode($newYyTime),
                            'update_time' => time()
                        ]);
                }
            }
            
            // 3. 发送企业微信通知
            $qyWechat = new QyWechatController($app);
            $startTime = $request['yy_time'][0];
            $endTime = end($request['yy_time']);
            $stopTime = date('H:i', strtotime($endTime) + 30 * 60);
            
            $res = $qyWechat->index('cancelReservationAction', [
                'mobile' => Db::name('shop_person')->where('id', $bookInfo['shop_person_id'])->value('phone'),
                'start' => $request['yy_date'] . ' ' . $startTime,
                'end' => $stopTime,
                'customer_name' => Db::name('customer')->where('id', $bookInfo['customer_id'])->value('customer_name')
            ]);
            
            Db::commit();
            return ['error' => '取消成功', 'data' => ['msg' => '取消成功']];
            
        } catch (\Exception $e) {
            Db::rollback();
            return ['error' => '取消失败: ' . $e->getMessage()];
        }

    }

    // 获取setting 14
    public function getSetting14($request): array
    {
        $category_id = $request['category_id'];

        $where = [];

        array_push($where,['category_id','=',$category_id]);

        $res = Db::name('setting')->where($where)->column('id,name');

        return $res;
    }
    
    
    /**
     * 一次性设置一周排班
     */
    public function setScheduleWeek($request)
    {
        // 验证必需参数
        if (empty($request['shop_id']))
        {
            return json(['code' => 400, 'msg' => '门店ID不能为空']);
        }
        if (empty($request['shop_person_id']))
        {
            return json(['code' => 400, 'msg' => '员工ID不能为空']);
        }
        // 获取店铺信息
        $shopInfo = Db::name('shop')
            ->where('shop_id', $request['shop_id'])
            ->field('start_time, end_time, time_default, is_schedule_appoint, am_work, pm_work')
            ->find();
            
        if (!$shopInfo)
        {
            return json(['code' => 404, 'msg' => '门店信息不存在']);
        }
        // 生成15天日期 (当天 + 未来14天)
        $dateList = [];
        $current = time();
        for ($i = 0; $i < 15; $i++)
        {
            $dateList[] = date('Ymd', $current + 86400 * $i);
        }
        // 生成可预约时间段
        $kkTime = $this->generateKkTime($shopInfo['start_time'],$shopInfo['end_time'],$shopInfo['time_default'],$shopInfo['is_schedule_appoint'],false);
    
        // 处理排班
        $successCount = 0;
        $skipCount = 0;
        $currentTime = time();
    
        foreach ($dateList as $date)
        {
            // 检查是否已有排班
            $schedule = Db::name('shop_person_schedule')
                ->where('shop_person_id', $request['shop_person_id'])
                ->where('time', $date)
                ->find();
    
            // 检查是否已有预约
            $hasAppointment = false;
            if ($schedule && !empty($schedule['yy_time']))
            {
                $yyTimeArr = json_decode($schedule['yy_time'], true);
                if ($yyTimeArr)
                {
                    foreach ($yyTimeArr as $appointedTime)
                    {
                        if (!in_array($appointedTime, $kkTime))
                        {
                            $hasAppointment = true;
                            break;
                        }
                    }
                }
            }
    
            // 准备排班数据
            $scheduleData = [
                'time' => $date,
                'shop_id' => $request['shop_id'],
                'shop_person_id' => $request['shop_person_id'],
                'is_work' => 1, // 上班
                'work_type' => 0, // 全天班
                'kk_time' => json_encode($kkTime),
                'update_time' => $currentTime
            ];
    
            // 存在排班记录
            if ($schedule)
            {
                if ($hasAppointment)
                {
                    $skipCount++;
                    continue; // 跳过有预约冲突的日期
                }
                
                $result = Db::name('shop_person_schedule')
                    ->where('id', $schedule['id'])
                    ->update($scheduleData);
            // 新排班记录
            }else
            {
                $scheduleData['create_time'] = $currentTime;
                
                $result = Db::name('shop_person_schedule')
                    ->insert($scheduleData);
            }
    
            if ($result)
            {
                $successCount++;
            }else
            {
                $skipCount++;
            }
        }
    
        return json([
            'code' => 200,
            'msg' => "排班完成，成功: {$successCount}天，跳过: {$skipCount}天",
            'data' => [
                'success' => $successCount,
                'skip' => $skipCount
            ]
        ]);
    }
    
    
    //可预约时间段
    public function getShiftTimeSlots($request)
    {
        // 验证必需参数
        $requiredFields = [
            'shop_id' => '门店ID'
        ];
        
        foreach ($requiredFields as $field => $name)
        {
            if (empty($request[$field])) {
                return json(['code' => 400, 'msg' => $name . '不能为空']);
            }
        }
    
        // 获取店铺信息
        $shopInfo = Db::name('shop')
            ->where('shop_id', $request['shop_id'])
            ->field('start_time, end_time, time_default, is_schedule_appoint, am_work, pm_work')
            ->find();

        if (!$shopInfo) {
            return json(['code' => 404, 'msg' => '门店信息不存在']);
        }
    
        // 生成三种班次类型的时间段
        $allDaySlots = [];
        $amSlots = [];
        $pmSlots = [];
        
        // 全天班
        $allDaySlots = $this->generateKkTime(
            $shopInfo['start_time'],
            $shopInfo['end_time'],
            $shopInfo['time_default'],
            $shopInfo['is_schedule_appoint'],
            true  // 表示需要处理结束时间点
        );
        
        // 上午班
        if (!empty($shopInfo['am_work'])) {
            list($amStart, $amEnd) = explode('-', $shopInfo['am_work']);
            $amSlots = $this->generateKkTime(
                trim($amStart),
                trim($amEnd),
                $shopInfo['time_default'],
                $shopInfo['is_schedule_appoint'],
                false  // 表示不需要处理结束时间点
            );
        }
        
        // 下午班
        if (!empty($shopInfo['pm_work'])) {
            list($pmStart, $pmEnd) = explode('-', $shopInfo['pm_work']);
            $pmSlots = $this->generateKkTime(
                trim($pmStart),
                trim($pmEnd),
                $shopInfo['time_default'],
                $shopInfo['is_schedule_appoint'],
                true  // 表示需要处理结束时间点
            );
        }
    
        // 获取排班状态
        $yyTime = [];
        $ddTime = [];
        
        if (!empty($request['shop_person_id']) && !empty($request['time']))
        {
            // 转换日期格式 (YYYYMMDD → YYYY-MM-DD)
            $dateString = (string)$request['time'];
            $year = substr($dateString, 0, 4);
            $month = substr($dateString, 4, 2);
            $day = substr($dateString, 6, 2);
            $start_time = "{$year}-{$month}-{$day} 00:00:00";
            $end_time = "{$year}-{$month}-{$day} 23:59:59";
            $startTimestamp = strtotime($start_time);
            $endTimestamp = strtotime($end_time);
        
            // 查询预约记录
            $books = Db::name('books')
                ->where('shop_person_id', $request['shop_person_id'])
                ->where('shop_id', $request['shop_id'])
                ->where('yy_time', '>=', $startTimestamp)
                ->where('yy_time', '<=', $endTimestamp)
                ->where('is_use', 1)
                ->select();
            if(!empty($books))
            {
                // 处理预约时间段
                foreach ($books as $book) {
                    if (!empty($book['yy_time_str'])) {
                        $slots = explode(',', $book['yy_time_str']);
                        foreach ($slots as $slot) {
                            $slot = trim($slot);
                            if ($slot) {
                                $bookedSlots[] = $slot;
                            }
                        }
                    }
                }
            }
        
            // 获取排班数据
            $schedule = Db::name('shop_person_schedule')
                ->where('shop_person_id', $request['shop_person_id'])
                ->where('time', $request['time'])
                ->field('yy_time, dd_time')
                ->find();
        
            if ($schedule)
            {
                $yyTime = json_decode($schedule['yy_time'] ?? '[]', true) ?: [];
                $ddTime = json_decode($schedule['dd_time'] ?? '[]', true) ?: [];
            }
            
            if(!empty($bookedSlots))
            {
                $yyTime = array_merge($yyTime, $bookedSlots);
            }
        }
    
        // 构建返回数据结构
        $buildSlots = function($slots) use ($yyTime, $ddTime)
        {
            $result = [];
            foreach ($slots as $timeSlot) {
                $result[] = [
                    'showTime' => $timeSlot,
                    'kk_time' => 1,
                    'yy_time' => in_array($timeSlot, $yyTime) ? 1 : 0,
                    'dd_time' => in_array($timeSlot, $ddTime) ? 1 : 0
                ];
            }
            return $result;
        };
    
        return [
            'day' => $buildSlots($allDaySlots),  // 全天班
            'am'  => $buildSlots($amSlots),      // 上午班
            'pm'  => $buildSlots($pmSlots)       // 下午班
        ];
    }
    
    
    
    
    
    /**
     * 内置方法 - 生成可预约时间段
     */
    private function generateKkTime($startTime, $endTime, $timeType, $is_schedule_appoint, $isEndPointHandling = true)
    {
        // 保存原始结束时间用于后续比较
        $originalEndTime = $endTime;
        
        // 将时间字符串转换为分钟数
        list($startHour, $startMin) = explode(':', $startTime);
        list($endHour, $endMin) = explode(':', $endTime);
        
        $startMinutes = (int)$startHour * 60 + (int)$startMin;
        $endMinutes = (int)$endHour * 60 + (int)$endMin;
        
        $timeSlots = [];
        
        // 根据时间类型确定间隔和取整方式
        if ($timeType == 2) { // 整点预约
            $startMinutes = ceil($startMinutes / 60) * 60;   // 向上取整到整点
            $endMinutes = floor($endMinutes / 60) * 60;     // 向下取整到整点
            $interval = 60;
        } else { // 半点预约（默认）
            $startMinutes = ceil($startMinutes / 30) * 30;   // 向上取整到半小时
            $endMinutes = floor($endMinutes / 30) * 30;     // 向下取整到半小时
            $interval = 30;
        }
        
        // 检查调整后时间范围有效性
        if ($startMinutes > $endMinutes) {
            return $timeSlots;
        }
        
        // 生成时间段
        $current = $startMinutes;
        while ($current <= $endMinutes) {
            $hour = floor($current / 60);
            $minute = $current % 60;
            $timeSlots[] = sprintf('%02d:%02d', $hour, $minute);
            $current += $interval;
        }
        
        // 处理结束时间点：只有需要处理时才执行
        if ($isEndPointHandling && !empty($timeSlots)) {
            $lastSlot = end($timeSlots);
            
            // 将时间转换为分钟数比较
            list($lastHour, $lastMin) = explode(':', $lastSlot);
            $lastMinutes = (int)$lastHour * 60 + (int)$lastMin;
            
            list($origEndHour, $origEndMin) = explode(':', $originalEndTime);
            $origEndMinutes = (int)$origEndHour * 60 + (int)$origEndMin;
            
            // 判断是否为结束时间边界
            $isEndBoundary = ($lastMinutes === $origEndMinutes);
            
            // 整点预约模式
            if ($timeType == 2) {
                // 结束时间点不可预约或不是整点
                if ($is_schedule_appoint == 0 || $lastMin != '00') {
                    // 移除边界点
                    if ($isEndBoundary) {
                        array_pop($timeSlots);
                    }
                }
            }
            // 半点预约模式
            else {
                // 结束时间点不可预约或不是半点
                if ($is_schedule_appoint == 0 || $lastMin != '30') {
                    // 移除边界点
                    if ($isEndBoundary) {
                        array_pop($timeSlots);
                    }
                }
            }
        }
        
        return $timeSlots;
    }


    // 获取市场的门店id列表
    public function getShopIds($request)
    {

        $marketId = $request['marketId'];

        $where = [];
        // array_push($where,['market_id','in',$marketId]);
        array_push($where,['type','<>','2']);
        array_push($where,['status','=','1']);
        array_push($where,['shop_type','=','2']);

        $shop_ids = Db::name('shop')->where($where)->column('shop_id');

        array_push($shop_ids,73782776653608);

        // echo "<pre>";
        // print_r($shop_ids);
        // echo "</pre>";
        return $shop_ids;
    }

    // 获取轮播图展示列表
    public function getBannerList($request){
        $where = [];

        if($request['type'] == 'mini'){
            array_push($where,['use_status','=','1']);
        }

        $list = Db::name('mini_banner')->where($where)->select()->toArray();

        $data = [];

        $data['list'] = $list ?? [];

        $data['dataCount'] = $dataCount ?? 0;

        return $data;
    }

    public function addPointLogs($request)
    {
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
		$paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 10;

        $customer_id = $request['customer_id'];

        $origin = Db::name('customer_point_origin')->where([['status','=',1],['change_type','=',1]])->column('id,message,num,change_type','id');

        $origin_ids = array_values(array_unique(array_column($origin,'id')));

        $where = [];

        array_push($where,['customer_id','=',$customer_id]);
        array_push($where,['origin_id','in',$origin_ids]);

        $dataCount = Db::name('customer_point_log')->where($where)->count();

        $logs = Db::name('customer_point_log')
                ->where($where)
                ->order('id DESC')
                ->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])
                ->select()->toArray();

        // echo "<pre>";
        // print_r($logs);
        // echo "</pre>";
        // exit;

        $list = [];
        foreach ($logs as $key => $value) {
            $one = [];

            $one['message'] = $origin[$value['origin_id']]['message'];
            $one['change_type'] = $origin[$value['origin_id']]['change_type'] == 1 ? '+' : '-';
            $one['point'] = $value['point'];
            $one['created_at'] = date('Y-m-d H:i:s',$value['created_at']);

            array_push($list,$one);
        }

        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";
        // exit;

        return [
            'list' => $list,
            'dataCount' => $dataCount,
        ];



    }

    public function spendPointLogs($request)
    {
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
		$paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 10;

        $customer_id = $request['customer_id'];

        $origin = Db::name('customer_point_origin')->where([['status','=',1],['change_type','=',2]])->column('id,message,num,change_type','id');

        $origin_ids = array_values(array_unique(array_column($origin,'id')));

        $where = [];

        array_push($where,['customer_id','=',$customer_id]);
        array_push($where,['origin_id','in',$origin_ids]);

        $dataCount = Db::name('customer_point_log')->where($where)->count();

        $logs = Db::name('customer_point_log')
                ->where($where)
                ->order('id DESC')
                ->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])
                ->select()->toArray();

        // echo "<pre>";
        // print_r($logs);
        // echo "</pre>";
        // exit;

        $list = [];
        foreach ($logs as $key => $value) {
            $one = [];

            $one['message'] = $origin[$value['origin_id']]['message'];
            $one['change_type'] = $origin[$value['origin_id']]['change_type'] == 1 ? '+' : '-';
            $one['point'] = $value['point'];
            $one['created_at'] = date('Y-m-d H:i:s',$value['created_at']);

            array_push($list,$one);
        }

        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";
        // exit;

        return [
            'list' => $list,
            'dataCount' => $dataCount,
        ];
    }


}
